package com.xyz.mockapi.importexcel.controller;

import com.xyz.mockapi.common.util.ImportType;
import com.xyz.mockapi.importexcel.service.ImportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/excel")
public class ImportExcelController {

    private final ImportService importService;

    public ImportExcelController(ImportService importService) {
        this.importService = importService;
    }

    @PostMapping("/import")
    public String importExcel(
            @RequestParam("type") String type,
            @RequestParam("file") MultipartFile file) {

        try {
            ImportType importType = ImportType.fromCode(type);
            if (importType == null) {
                return "不支持的导入类型: " + type;
            }

            // 调用导入方法（此时ExcelUtil已拦截解析错误）
            return switch (importType) {
                case BD_SUB_PRODUCT_TYPE -> importService.importBdSubProductType(file);
                case ONLINE_BOM -> importService.importOnlineBom(file);
                case ONLINE_PRODUCT -> importService.importOnlineProduct(file);
                default -> "不支持的导入类型: " + type;
            };

        } catch (RuntimeException e) {
            // 捕获ExcelUtil抛出的中文错误提示（如"第2行，第10列【fIsfirst（1工单首台 0非工单首台）】字段值【ok】错误..."）
            return e.getMessage();
        } catch (IOException e) {
            return "导入失败: 文件读取错误 - " + e.getMessage();
        } catch (Exception e) {
            return "导入失败: 系统错误 - " + e.getMessage();
        }
    }
}